package com.pencilisland.pay.core.mp.service.impl;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pencilisland.pay.api.bean.constant.OrderConstant;
import com.pencilisland.pay.api.bean.mp.core.MessageRequest;
import com.pencilisland.pay.api.bean.mp.core.MessageResponse;
import com.pencilisland.pay.api.bean.mp.core.UpdateOrderREQ;
import com.pencilisland.pay.api.bean.mp.core.UpdateOrderRES;
import com.pencilisland.pay.api.bean.mp.mgt.SyncOrderREQ;
import com.pencilisland.pay.api.bean.mp.mgt.SyncOrderRES;
import com.pencilisland.pay.api.bean.wxpay.WxTemplate;
import com.pencilisland.pay.api.bean.wxpay.WxpayCloseOrderReq;
import com.pencilisland.pay.api.entity.TradeOrderEntity;
import com.pencilisland.pay.api.repository.TradeOrderRepository;
import com.pencilisland.pay.api.service.WxpayService;
import com.pencilisland.pay.core.mp.service.MBService;
import com.pencilisland.pay.core.service.RestService;
import com.pencilisland.pay.core.service.WxappService;

/**
 * 报文逻辑处理.更新订单状态
 *
 * @author breeze
 */
@Service("MB_updateOrder")
public class UpdateOrderMB implements MBService {
	
	Logger log = LoggerFactory.getLogger(getClass());

	@Autowired
	ObjectMapper objectMapper;
	@Autowired
	TradeOrderRepository tradeOrderRepo;
	@Autowired
	WxpayService wxpayService;
	@Autowired
	RestService restService;
	@Autowired
	WxappService wxappService;

	@Override
	public MessageResponse process(MessageRequest request) {
		
		
		UpdateOrderREQ requestBean = getRequestBody(request);

		for (UpdateOrderREQ.ElementOrders order : requestBean.getOrders()) {
			
			log.info("订单【{}】状态更新【{}】",order.getOrderNo(),order.getStatus());

			TradeOrderEntity tradeOrder = tradeOrderRepo.findOne(order.getOrderNo());
			if (tradeOrder == null)
				continue;

			if(order.getStatus() == OrderConstant.STATUS_2){//发货
				tradeOrder.setStatus(order.getStatus());
				tradeOrder.setTrackingNumber(order.getTrackingNumber());
				tradeOrderRepo.save(tradeOrder);
				
				//发送推送模板消息
				WxTemplate wxTemplate = new WxTemplate();
				wxTemplate.setToUser(tradeOrder.getOpenId());
				wxTemplate.setFormId(tradeOrder.getPrepayId());
				wxTemplate.setTemplateId(OrderConstant.SEND_TEMPLATE_ID);
				
				Map<String,Object> data = new HashMap<String,Object>();
				wxTemplate.setData(data);
				
				wxappService.sendTemplate(wxTemplate);
				
			}else if (order.getStatus() == OrderConstant.STATUS_3) {// 撤销
				// 退款处理
				tradeOrder.setStatus(OrderConstant.STATUS_3);
				tradeOrderRepo.save(tradeOrder);

			} else if (order.getStatus() == OrderConstant.STATUS_4) {// 关闭
				// 关闭订单
				WxpayCloseOrderReq closeReq = new WxpayCloseOrderReq();
				closeReq.setOutTradeNo(tradeOrder.getOrderNo());
				try {
					wxpayService.closeOrder(closeReq);
				} catch (Exception e) {
					e.printStackTrace();
				}
				
				tradeOrder.setPayStatus(OrderConstant.PAY_STATUS_3);
				tradeOrder.setStatus(OrderConstant.STATUS_4);
				tradeOrder.setFinishTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
				
				if("APP".equals(order.getFrom())){//同步到后台管理系统
					SyncOrderREQ syncOrder = new SyncOrderREQ();
					syncOrder.setOrderNo(order.getOrderNo());
					syncOrder.setType("auto_close");
					syncOrder.setStatus(OrderConstant.STATUS_4);
					SyncOrderRES syncOrderRes = restService.sendToMgtMP("syncOrder", syncOrder, SyncOrderRES.class);
					if(syncOrderRes.getSuccess()){
						tradeOrder.setSyncMgt("2");
					}
				}
				
				tradeOrderRepo.save(tradeOrder);
			}
		}

		UpdateOrderRES res = new UpdateOrderRES(true, null, "OK");
		return res;
	}

	public UpdateOrderREQ getRequestBody(MessageRequest request) {
		return objectMapper.convertValue(request.getBody(), UpdateOrderREQ.class);
	}

}
